﻿using Microsoft.AspNetCore.Mvc;
using StudentManagement.Infrastructure.Repositories;
using StudentManagement.Models;
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Linq.Dynamic.Core;
using Microsoft.EntityFrameworkCore;
using StudentManagement.Services;
using StudentManagement.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using StudentManagement.Extensions.Pagenation;
using StudentManagement.Utils;

namespace StudentManagement.Controllers
{
    [Authorize]
    public class StudentController : Controller
    {
        private readonly IRepository<Student> stuRepository;
        private readonly IStudentService studentService;

        public StudentController(IRepository<Student> repository, IStudentService studentService)
        {
            this.stuRepository = repository;
            this.studentService = studentService;
        }

        /// <summary>
        /// 返回所有学生列表
        /// </summary>
        /// <returns></returns>
        public IActionResult Index(PageParameters pageParameters)
        {
            ViewBag.PageTitle = "学生信息列表";
            ViewBag.SortBy = pageParameters.SortBy.Trim();
            ViewBag.SearchString = pageParameters.SearchString?.Trim();

            var model = studentService.GetPagedData(pageParameters);

            CurrentUser.UserName = HttpContext.Session.GetString("CurrentUser");
            return View(model);
        }

        public IActionResult Details(int id)
        {
            var student = stuRepository.Get(id);
            if (student != null) {
                ViewBag.PageTitle = "学生信息详情页";
                return View(student);
            }
            else {
                Response.StatusCode = 404;
                return View("StudentNotFound", id);
            }

        }

        public IActionResult Error()
        {
            throw new Exception("出现未知错误");
        }

        [HttpGet]
        public IActionResult Create()
        {
            ViewBag.PageTitle = "新增学生数据";
            return View();
        }

        [HttpPost]
        public IActionResult Create(Student student)
        {
            if (ModelState.IsValid) {
                stuRepository.Insert(student);
                return RedirectToAction("Index");
            }

            ViewBag.PageTitle = "新增学生数据";
            return View();
        }

        [HttpGet]
        public IActionResult Edit(int id)
        {
            var student = stuRepository.Get(id);
            ViewBag.PageTitle = "编辑学生数据";
            return View(student);
        }

        [HttpGet]
        public IActionResult AddOrEdit(int id = 0)
        {
            if (id == 0) {
                return View(new Student());
            }
            else {
                var student = stuRepository.Get(id);
                if (student == null) {
                    return NotFound();
                }
                return View(student);
            }
        }

        [HttpPost]
        public IActionResult AddOrEdit(int id, Student student)
        {
            if (ModelState.IsValid) {
                if (id == 0) { // 新增
                    stuRepository.Insert(student);
                }
                else {
                    stuRepository.Update(student);
                }

                return Json(new
                {
                    isValid = true,
                    html = AjaxHelper.RazorViewToString(this, "ViewAll",
                            studentService.GetPagedData(new PageParameters()))
                });
            }
            return Json(new
            {
                isValid = false,
                html = AjaxHelper.RazorViewToString(this, "AddOrEdit", stuRepository.Get(id))
            });
        }

        [HttpPost]
        public IActionResult Edit(Student student)
        {
            if (ModelState.IsValid) {
                stuRepository.Update(student);
                return RedirectToAction("Index");
            }
            return View();
        }

        [HttpGet]
        public IActionResult Delete(int id)
        {
            return View();
        }

        [HttpPost, ActionName("Delete")]
        public IActionResult DeleteConfirmed(int id)
        {
            var student = stuRepository.Get(id);
            if (student != null) {
                stuRepository.Delete(student);
                return Json(new { html = AjaxHelper.RazorViewToString(
                    this, "ViewAll", studentService.GetPagedData(new PageParameters())) 
                });
            }

            return View();
        }

        [HttpGet]
        public IActionResult About()
        {
            var data = from student in stuRepository.GetAll()
                       group student by student.EnrollmentDate into dateGroup
                       select new StudentStatistics()
                       {
                           EnrollmentDate = dateGroup.Key,
                           StudentCount = dateGroup.Count()
                       };

            var model = data.AsNoTracking().ToList();

            return View(model);
        }
    }
}
